<template>
  <a-spin :loading="data.loading">
    <a-table :data="data.tableData" :pagination="false">
      <template #columns>
        <a-table-column title="序号" align="center" :width="80">
          <template #cell="{ rowIndex }">{{ rowIndex + 1 }}</template>
        </a-table-column>
        <a-table-column title="告警来源" data-index="alarmType" align="center">
          <template #cell="{ record }">
            {{ alarmTypeList.map((item) => item.name)[record.alarmType] }}
          </template>
        </a-table-column>
        <a-table-column title="卫星" data-index="satName" align="center" />
        <a-table-column title="设备" data-index="deviceName" align="center" />
        <a-table-column title="参数" data-index="paramName" align="center" />
        <a-table-column title="告警名称" data-index="tempName" align="center" />
        <!-- <a-table-column title="告警信息" data-index="info" align="center" /> -->
        <a-table-column title="首次告警时间" data-index="createTime" align="center" :width="200" />
        <a-table-column title="末次告警时间" data-index="endTime" align="center" :width="200" />
        <a-table-column title="次数" data-index="times" align="center" />
        <a-table-column title="操作" align="center">
          <template #cell="{ record }">
            <a-space size="mini">
              <a-button v-if="record.status === 0" type="text" status="success" @click="handleShield(record, 1)"
                >屏蔽
              </a-button>
              <a-button v-else type="text" status="success" @click="handleShield(record, 0)">取消屏蔽 </a-button>
              <a-button type="text" status="warning" @click="handleDelete(record)">删除 </a-button>
              <a-button type="text" @click="handleSuggestion(record)">处置策略建议 </a-button>
            </a-space>
          </template>
        </a-table-column>
      </template>
    </a-table>
    <a-pagination
      class="my-1"
      style="float: right; margin-right: 20px; margin-top: 20px; justify-content: end"
      :total="data.paginationData.total"
      :current="data.paginationData.pageNum"
      :page-size="data.paginationData.pageSize"
      show-total
      show-jumper
      show-page-size
      @change="handleCurrentChange"
      @page-size-change="handleSizeChange"
    />
  </a-spin>
  <a-modal v-if="data.visible" title="处置策略建议" v-model:visible="data.visible" width="600px" @ok="handleProcess">
    <div
      v-for="(item, index) in content"
      :key="index"
      :class="['Suggestion-class', { active: activeIndex === index }]"
      @click="handleClickSolutionDesc(item, index)"
    >
      {{ item.solutionDesc }}
    </div>
  </a-modal>
</template>

<script setup>
import { onMounted, reactive, onBeforeUnmount, createVNode, ref } from 'vue'
import { apiHome } from '@/api/strategy'
import { apiAnalysis } from '@/api/analysis'
import { apiHome as indexApi } from '@/api/index'
import { apiTemplate } from '@/api/complexModel'
import { alarmTypeList } from '@/utils/alarmType'
import { Message, Modal, Notification } from '@arco-design/web-vue'

const props = defineProps({
  switchTabFunc: {
    type: Function,
    default: () => {}
  },
  currentTabKey: {
    type: String,
    default: ''
  }
})
const data = reactive({
  visible: false,
  loading: false,
  tableData: [],
  paginationData: {
    total: 0,
    pageNum: 1,
    pageSize: 10
  },
  params: {}
})

const getList = () => {
  apiHome.getAlarmSummary(data.paginationData).then((res) => {
    data.tableData = res.data.list
    data.paginationData.total = +res.data.total
  })
}
const handleCurrentChange = (page) => {
  data.paginationData.pageNum = page
  getList()
}
const handleSizeChange = (size) => {
  data.paginationData.pageSize = size
  getList()
}

const handleShield = (record, type) => {
  const apiMap = {
    0: indexApi.updateTemplateStatus,
    1: apiAnalysis.updateTemplateStatus,
    2: apiAnalysis.updateConstantMonitorStatus,
    3: apiTemplate.updateBindStatus,
    4: apiAnalysis.updateSequenceDataStatus
  }

  Promise.all([
    apiMap[record.alarmType]({
      id: [1, 3, 4].includes(record.alarmType) ? record.bindId : record.tempId,
      state: type === 1 ? 2 : 1 // 2:屏蔽 1:取消屏蔽
    }),
    apiHome.getShield({
      id: record.uuid,
      state: type // 0:取消屏蔽 1:屏蔽
    })
  ])
    .then((results) => {
      results.forEach((res, index) => {
        if (res.code === 200 && index === 1) {
          Message.success(type === 1 ? '屏蔽成功' : '取消屏蔽成功')
          getList()
        }
      })
    })
    .catch((error) => {
      console.error('请求失败:', error)
    })
}

const handleDelete = (record) => {
  Modal.confirm({
    title: '删除',
    content: '确定删除吗？',
    okText: '确定',
    cancelText: '取消',
    onOk: () => {
      apiHome.getDelete({ id: record.uuid }).then((res) => {
        if (res.code === 200) {
          Message.success('删除成功')
          getList()
        }
      })
    }
  })
}

const content = ref([])
const activeIndex = ref(-1)
const handleSuggestion = (record) => {
  apiHome.getStrategy(record.uuid).then((res) => {
    if (res.code === 200) {
      console.log(res.data)
      const params = {
        id: '',
        isAdopt: 1,
        solutionId: '',
        warningId: ''
      }
      data.visible = true
      activeIndex.value = -1
      content.value = res.data.map((item) => ({
        ...item,
        isActive: false
      }))
      // const content = res.data.map((item) => {
      //   return h(
      //     "div",
      //     {
      //       class: {
      //         "Suggestion-class": true,
      //         "Suggestion-class-active": true
      //       }, // 添加类名
      //       onClick: () => {
      //         aaa.value = true;
      //         params.id = item.id;
      //         params.solutionId = item.solutionId;
      //         params.warningId = item.warningId;
      //       },
      //     },
      //     item.solutionDesc
      //   );
      // });
      // Modal.info({
      //   title: "处置策略建议",
      //   content,
      //   width: 600,
      //   onOk: () => {
      //     console.log("OK clicked", params);
      //     if (params.solutionId) {
      //       apiHome.getStrategySelect(params).then((res) => {
      //         if (res.code === 200) {
      //           Message.success("采纳成功");
      //           getList();
      //         }
      //       });
      //     }
      //   },
      // });
    }
  })
}

const handleClickSolutionDesc = (item, index) => {
  // 更新点击的索引
  activeIndex.value = index

  // 更新参数
  data.params.id = item.id
  data.params.solutionId = item.solutionId
  data.params.warningId = item.warningId
}

const handleProcess = () => {
  apiHome.getStrategySelect(data.params).then((res) => {
    if (res.code === 200) {
      Message.success('采纳成功')
      getList()
    }
  })
}
let notification = null
const getAlarmInfo = () => {
  apiHome.getAlarmDetail().then((res) => {
    if (res.code === 200) {
      // console.log(res.data, "告警信息");
      // let uuidShowed = []
      // res.data = [1, 2, 3, 4, 5, 6, 6, 3, 4, 5, 6, 7, 8, 9, 8].map(() => {
      //   return {
      //     uuid: "1",
      //     satName: "Sat1",
      //     deviceName: "Device1",
      //     paramName: "Param1",
      //     tempName: "Temp1",
      //     endTime: "2023-07-01 12:00:00",
      //     tempId: "1",
      //     tempType: "1",
      //     tempValue: "30",
      //     tempUnit: "°C",
      //     tempDesc: "温度过高",
      //     tempSolution: "降低设备温度",
      //   }
      // })
      if (res.data.length > 0) {
        notification && notification.close()
        notification = Notification.warning({
          title: '告警通知',
          content: createVNode('div', { marginTop: '10px' }, [
            createVNode(
              'div',
              {
                style: {
                  marginBottom: '10px',
                  fontSize: '12px',
                  color: '#ff9700'
                }
              },
              `新增${res.data.length}条告警信息`
            ),
            createVNode(
              'ul',
              {
                style: {
                  maxHeight: '200px',
                  overflow: 'auto',
                  padding: '0px',
                  margin: '0px',
                  listStyleType: 'lower-roman',
                  color: '#666666'
                }
              },
              res.data.map((item, index) => {
                return createVNode(
                  'li',
                  {
                    style: {
                      marginBottom: '5px',
                      fontSize: '12px',
                      borderBottom: '1px dashed #cccccc',
                      padding: '5px'
                    }
                  },
                  [
                    createVNode('b', {}, `${index + 1}：`),
                    `${item.satName}卫星${item.deviceName}设备中的${item.paramName}参数，在${item.endTime}发生了${item.tempName}告警`
                  ]
                )
              })
            ),
            props.currentTabKey !== 'warning' &&
              createVNode(
                'button',
                {
                  class: 'arco-btn arco-btn-text arco-btn-shape-square arco-btn-size-medium arco-btn-status-normal',
                  onclick: () => {
                    props.switchTabFunc('warning')
                    notification.close()
                  },
                  fontSize: '12px',
                  color: '#1890ff'
                },
                `查看所有告警`
              )
          ]),
          position: 'bottomRight',
          closable: true,
          duration: 10000
        })
      }
    }
  })
}

let intervalId = null

onBeforeUnmount(() => {
  intervalId && clearInterval(intervalId)
})

onMounted(() => {
  getList()
  intervalId = setInterval(() => {
    getAlarmInfo()
  }, 5000)
  getAlarmInfo()
})
</script>

<style scoped>
.arco-btn-text.arco-btn-status-success:hover {
  color: #00b3b3;
}

:deep(.arco-btn-text.arco-btn-status-success.arco-btn-disabled) {
  color: var(--color-success-light-3);
  background-color: transparent;
  border: 0.005208rem solid transparent;
}

.Suggestion-class {
  cursor: pointer;
  padding: 4px 8px;
}

.Suggestion-class:hover {
  color: #fff;
  background-color: rgb(64, 128, 255, 0.5); /* 鼠标悬停时的背景颜色 */
}

.Suggestion-class-active {
  background: red;
}

.Suggestion-class.active {
  /* 激活样式 */
  color: #fff;
  background-color: #4080ff; /* 示例样式 */
}
</style>
